const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');

// 获取日志列表
router.get('/', async (req, res) => {
  try {
    console.log('日志列表路由被访问，参数:', req.query);
    const { 
      limit = 20, 
      page = 1, 
      userRole, 
      action, 
      startDate, 
      endDate,
      userId,
      userName,
      target
    } = req.query;
    
    let query = `
      SELECT * FROM logs
      WHERE 1=1
    `;
    
    const params = [];
    
    // 根据查询参数添加过滤条件
    if (userRole) {
      query += ` AND userRole = ?`;
      params.push(userRole);
    }
    
    if (action) {
      query += ` AND action = ?`;
      params.push(action);
    }
    
    if (target) {
      query += ` AND target = ?`;
      params.push(target);
    }
    
    if (userId) {
      query += ` AND userId = ?`;
      params.push(userId);
    }
    
    if (userName) {
      query += ` AND userName LIKE ?`;
      params.push(`%${userName}%`);
    }
    
    if (startDate) {
      query += ` AND timestamp >= ?`;
      params.push(startDate);
    }
    
    if (endDate) {
      query += ` AND timestamp <= ?`;
      params.push(endDate);
    }
    
    // 添加排序和分页
    query += ` ORDER BY timestamp DESC LIMIT ? OFFSET ?`;
    const pageSize = parseInt(limit);
    const offset = (parseInt(page) - 1) * pageSize;
    params.push(pageSize, offset);
    
    console.log('执行SQL查询:', query, params);
    
    const [rows] = await pool.query(query, params);
    console.log('日志查询结果数量:', rows.length);
    
    // 查询总数
    let countQuery = `SELECT COUNT(*) as total FROM logs WHERE 1=1`;
    const countParams = [];
    
    if (userRole) {
      countQuery += ` AND userRole = ?`;
      countParams.push(userRole);
    }
    
    if (action) {
      countQuery += ` AND action = ?`;
      countParams.push(action);
    }
    
    if (target) {
      countQuery += ` AND target = ?`;
      countParams.push(target);
    }
    
    if (userId) {
      countQuery += ` AND userId = ?`;
      countParams.push(userId);
    }
    
    if (userName) {
      countQuery += ` AND userName LIKE ?`;
      countParams.push(`%${userName}%`);
    }
    
    if (startDate) {
      countQuery += ` AND timestamp >= ?`;
      countParams.push(startDate);
    }
    
    if (endDate) {
      countQuery += ` AND timestamp <= ?`;
      countParams.push(endDate);
    }
    
    const [countResult] = await pool.query(countQuery, countParams);
    const total = countResult[0].total;
    
    res.json({
      logs: rows,
      pagination: {
        total,
        page: parseInt(page),
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      }
    });
  } catch (error) {
    console.error('获取日志列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取日志详情
router.get('/:id', async (req, res) => {
  try {
    const logId = req.params.id;
    console.log('日志详情路由被访问，日志ID:', logId);
    
    const query = `SELECT * FROM logs WHERE id = ?`;
    const [rows] = await pool.query(query, [logId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '日志不存在' });
    }
    
    res.json(rows[0]);
  } catch (error) {
    console.error('获取日志详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 添加日志
router.post('/', async (req, res) => {
  try {
    console.log('添加日志路由被访问，请求体:', req.body);
    const { 
      userId, 
      userName, 
      userRole, 
      action, 
      target, 
      targetId, 
      content, 
      ip 
    } = req.body;
    
    if (!userName || !userRole || !action || !target) {
      return res.status(400).json({ message: '缺少必要参数' });
    }
    
    const query = `
      INSERT INTO logs (userId, userName, userRole, action, target, targetId, content, ip, timestamp)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
    `;
    
    const [result] = await pool.query(query, [
      userId, 
      userName, 
      userRole, 
      action, 
      target, 
      targetId || null, 
      content || null, 
      ip || req.ip
    ]);
    
    res.status(201).json({
      message: '日志添加成功',
      logId: result.insertId
    });
  } catch (error) {
    console.error('添加日志失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取日志统计信息
router.get('/stats/summary', async (req, res) => {
  try {
    console.log('日志统计路由被访问');
    
    // 获取用户角色分布
    const roleQuery = `
      SELECT userRole, COUNT(*) as count
      FROM logs
      GROUP BY userRole
      ORDER BY count DESC
    `;
    
    // 获取操作类型分布
    const actionQuery = `
      SELECT action, COUNT(*) as count
      FROM logs
      GROUP BY action
      ORDER BY count DESC
    `;
    
    // 获取最近7天的日志数量
    const dailyQuery = `
      SELECT DATE(timestamp) as date, COUNT(*) as count
      FROM logs
      WHERE timestamp >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
      GROUP BY DATE(timestamp)
      ORDER BY date
    `;
    
    const [roleStats] = await pool.query(roleQuery);
    const [actionStats] = await pool.query(actionQuery);
    const [dailyStats] = await pool.query(dailyQuery);
    
    res.json({
      roleDistribution: roleStats,
      actionDistribution: actionStats,
      dailyActivity: dailyStats
    });
  } catch (error) {
    console.error('获取日志统计失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 清除指定日期之前的日志
router.delete('/clear', async (req, res) => {
  try {
    console.log('清除日志路由被访问，参数:', req.query);
    const { beforeDate } = req.query;
    
    if (!beforeDate) {
      return res.status(400).json({ message: '缺少必要参数' });
    }
    
    const query = `DELETE FROM logs WHERE timestamp < ?`;
    const [result] = await pool.query(query, [beforeDate]);
    
    res.json({
      message: '日志清除成功',
      deletedCount: result.affectedRows
    });
  } catch (error) {
    console.error('清除日志失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

module.exports = router;